<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://erdangjiade.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: xiaojie <997031758@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 菜单模型
// +----------------------------------------------------------------------
namespace app\admin\model;


use \think\Model;

class Menu extends Model
{
    protected $autoWriteTimestamp = true;

    public function parent()
    {
        return $this->belongsTo(Menu::class,'parent_id','id');
    }

    public static  function onBeforeWrite(Menu $menu)
    {
        if (empty($menu->parent_id)) {
            $menu->level = 0;
            $menu->path  = '-';
        } else {
            $menu->level = $menu->parent->level + 1;
            $menu->path  = $menu->parent->path.$menu->parent_id.'-';
        }
    }

    public function getMenuList($parent_id = 0,&$data=[],&$level=0)
    {

        if(Admin::userId() == 1){
            $menus = $this->where(['parent_id'=>$parent_id,'status'=>1,'is_menu'=>1])->order('sort')->select();
        }else{
            $group_ids = AuthGroupAccess::where('admin_id',Admin::userId())->column('auth_group_id');
            $rules = AuthRule::where('auth_group_id','in',$group_ids)->column('rule');
            $menus = $this->where(['parent_id'=>$parent_id,'status'=>1,'is_menu'=>1])
                ->where('id','in',$rules)
                ->order('sort')->select();
        }


        if(isset($menus) and !empty($menus)){
            foreach ($menus as $menu){
                $data[$menu->id.$menu->app] = [
                    "menuid" => $menu->id,
                    "id" => $menu->id . $menu->app,
                    "title" => $menu->title,
                    "icon" => $menu->icon,
                    "parent" => $menu->parent_id,
                    "url" => "/{$menu->app}/{$menu->controller}/{$menu->action}"
                ];
                $children = $this->getMenuList($menu->id);
                if (!empty($children) && $level < 3) {
                    $data[$menu->id.$menu->app]['items'] = $children;
                }
            }
        }
        return $data;
    }

}
